package com.ma4567.remotecontroller.LoginRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ma4567.remotecontroller.MysqlHelper.TableLogManager;
import com.ma4567.remotecontroller.MysqlHelper.TableRequestLog;
import com.ma4567.remotecontroller.UserManager.UserPermission;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import com.ma4567.remotecontroller.RemoteControllerApplication;

import java.sql.SQLException;

class LoginReturnIndex{
    public int Status;
    public String Cookie;

    public LoginReturnIndex(int status, String cookie){
        this.Status = status;
        this.Cookie = cookie;
    }
}

@CrossOrigin
@RestController
public class Login {
    //return status and cookie
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String LoginVerify(HttpServletRequest request,
                              @RequestParam("account") String AccountOrName,
                              @RequestParam("password") String password) throws SQLException {
        TableRequestLog.AddLog("Login", AccountOrName, request.getRemoteAddr());
        if(RemoteControllerApplication.userManager.UserVerify(AccountOrName, password))
        {
            String cookie = RemoteControllerApplication.userManager.UserLogin(AccountOrName, password);

            if(cookie.equals("null")){
                return JSONObject.toJSONString(new LoginReturnIndex(1, "null"), SerializerFeature.PrettyFormat);
            }
            else{
                TableLogManager.AddLog("Login", cookie);
                return JSONObject.toJSONString(new LoginReturnIndex(0, cookie), SerializerFeature.PrettyFormat);
            }
        }
        else
        {
            return JSONObject.toJSONString(new LoginReturnIndex(2, "null"), SerializerFeature.PrettyFormat);
        }
    }
}
